#include "widget.h"
#include "ui_widget.h"
#include "operate_image.h"
#include <QFileDialog>
#include <string>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->start_button->setEnabled(false);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::dp_message(QString message, message_type type)
{
    ui->message_box->setText(message);

    QPalette palette;
    switch (type) {
    case message_type::ordinary:
        palette.setColor(QPalette::WindowText, Qt::black);
        break;

    case message_type::all_right:
        palette.setColor(QPalette::WindowText, Qt::green);
        break;

    case message_type::warning:
        palette.setColor(QPalette::WindowText, Qt::red);
        break;
    }
    ui->message_box->setPalette(palette);
}

void Widget::clear_status()
{
    ui->image_path->setText(QString());
    ui->start_button->setEnabled(false);
    ui->start_button->setText(QString("无操作"));
}

void Widget::on_choose_image_clicked()
{
    ui->image_path->setText(QFileDialog::getOpenFileName(this, QString("选择一个加密或未加密的图片"),
                                                         QString("~/Pictures"), QString("图片文件(*.png *.jpg *.jpeg *.tga *.bmp)"))
                            );
}

void Widget::on_start_button_clicked()
{
    operate_image(ui->image_path->text());
}

void Widget::on_image_path_textChanged(const QString &arg1)
{
    std::string image_path_s = arg1.toStdString();

    bool is_encrypted = false;
    int i=0;
    for (auto ptr = image_path_s.end()-1; ptr>=image_path_s.begin()-1; ptr--) {
        if (*ptr=='.') {
            if (i==0) {
                i++;
            }
            else {
                is_encrypted = true;
                break;
            }
        }
    }

    if(is_encrypted) {
        ui->start_button->setEnabled(true);
        ui->start_button->setText("解密图片");
    }
    else {
        ui->start_button->setEnabled(true);
        ui->start_button->setText("加密图片");
    }
}
